package com.lanhao.aot.jwt;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Maps;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.UnsupportedJwtException;

public class JwtUtils {
	private static final Logger log = LoggerFactory.getLogger(JwtUtils.class);

	/**
	 * 生成token信息并返回
	 * 
	 * @param claims
	 * @return
	 */
	public static Map<String, Object> generateToken(Map<String, Object> claims) {
		if (Objects.isNull(claims)) {
			claims = new HashMap<>(16);
		}
		Map<String, Object> map = new HashMap<>(16);
		Date date = new Date(System.currentTimeMillis() + JwtConstant.EXPIRATION_TIME * 1000);
		log.info("过期时间：{}", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
		String jwt = Jwts.builder().setClaims(claims).setExpiration(date)
				.signWith(SignatureAlgorithm.HS512, JwtConstant.SECRET).compact();
		log.debug("生成的token:{}", jwt);
		map.put("token", JwtConstant.TOKEN_PREFIX + " " + jwt);
		map.put("tokenType", JwtConstant.TOKEN_PREFIX);
		map.put("expireTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
		return map;
	}

	 /**
     * 检验并解析token
     * IllegalArgumentException:JWT字符串参数不能为空或null。
     * SignatureException:字符串伪造 并不是服务端颁发的token
     * MalformedJwtException:字符串缺失
     * ExpiredJwtException：token已过期
     * UnsupportedJwtException:未知
     */
	public static Object validateTokenAndGetClaims(String token) {
		Map<String, Object> body = null;
		try {
			body = Jwts.parser().setSigningKey(JwtConstant.SECRET)
					.parseClaimsJws(token.replace(JwtConstant.TOKEN_PREFIX, "")).getBody();
		} catch (UnsupportedJwtException e) {
			e.printStackTrace();
		}
		return body;
	}
	
	public static void main(String[] args) {
		
		Map<String, Object> claimMap = Maps.newHashMap();
		claimMap.put("openId", "xxxxxxxxxxxxx");
		claimMap.put("userId", 1L);
        Map<String, Object> generateToken = JwtUtils.generateToken(claimMap);
        
        System.out.println(generateToken);
        
		Object validateTokenAndGetClaims = validateTokenAndGetClaims((String) generateToken.get("token") + "xxx");
		
		System.out.println(validateTokenAndGetClaims);
	}
}
